package com.steven.simple;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

/**
 * 自定义handler需要继承netty中规定好的某个handleradapter
 */
public class NettyServerHandler  extends ChannelInboundHandlerAdapter {

    /**
     * @param ctx 包含上下文对象，管道，通道，地址
     * @param msg 客户端发送的数据，默认是object
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        ctx.channel().eventLoop().execute(() -> {
            try {
                Thread.sleep(50*1000);
                ctx.writeAndFlush(Unpooled.copiedBuffer("你好",CharsetUtil.UTF_8));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });


//        System.out.println(ctx);
//        //netty提供的
//        ByteBuf byteBuffer = (ByteBuf) msg;
//        System.out.println("接受到客户端数据："+ byteBuffer.toString(CharsetUtil.UTF_8));
//        System.out.println("地址："+ctx.channel().remoteAddress());
//        super.channelRead(ctx, msg);
    }

    //数据读写完成
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        //将数据写入到缓存，并刷新
        ctx.writeAndFlush(Unpooled.copiedBuffer("你好",CharsetUtil.UTF_8));
//        super.channelReadComplete(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
//        super.exceptionCaught(ctx, cause);
    }
}
